import { post } from "@/utils/http";
import { ref, unref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

export function useHttp<T>(url: string, initialParams: any) {
  const dataList = ref<T[]>([]);
  const loading = ref<boolean>(false);
  const totals = ref<number>(0);
  const pageInfo = reactive({
    page: 1,
    pageSize: 10,
  });

  const loadData = async () => {
    loading.value = true;
    try {
      const {
        data: { list, total },
      } = await post(url, { ...unref(initialParams), ...pageInfo });
      dataList.value = list;
      totals.value = total;
    } catch (err) {
      console.log(err);
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    loadData();
  });

  const handleSizeChange = (val: number) => {
    pageInfo.pageSize = val;
    loadData();
  };

  const handleCurrentChange = (val: number) => {
    pageInfo.page = val;
    loadData();
  };

  const resetPagination = () => {
    pageInfo.page = 1;
    pageInfo.pageSize = 10;
    loadData();
  };
  return {
    dataList,
    loading,
    totals,
    pageInfo,
    loadData,
    handleSizeChange,
    handleCurrentChange,
    resetPagination,
  };
}
